package com.suyeer.basic.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @author jun 2018/10/19
 */
public class LogUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(LogUtil.class);

    public static String getErrorLocation(Exception exception) {
        try {
            StackTraceElement stackTraceElement = getStackTraceElement(exception);
            return String.format("%s.%s(%s:%s)",
                    stackTraceElement.getClassName(),
                    stackTraceElement.getMethodName(),
                    stackTraceElement.getFileName(),
                    stackTraceElement.getLineNumber());
        } catch (Exception e) {
            return null;
        }
    }

    public static StackTraceElement getStackTraceElement(Exception exception) {
        try {
            return exception.getStackTrace()[0];
        } catch (Exception e) {
            return null;
        }
    }

    public static void info(String msg) {
        LOGGER.info(msg);
    }

    public static void info(String format, Object... arguments) {
        LOGGER.info(format, arguments);
    }

    public static void error(String msg) {
        LOGGER.error(msg);
    }

    public static void error(String format, Object... arguments) {
        LOGGER.error(format, arguments);
    }

    public static void error(Exception exception, String format, Object... arguments) {
        for (Object object : arguments) {
            format = format.replaceFirst("\\{\\}", Objects.toString(object));
        }
        error(format, exception);
    }

    public static void error(Exception exception) {
        error(exception.getMessage(), exception);
    }

    public static void error(String msg, Exception exception) {
        StackTraceElement stackTraceElement = getStackTraceElement(exception);
        error("{}({}:{}:{})",
                msg,
                exception.getClass().getName(),
                stackTraceElement.getFileName(),
                stackTraceElement.getLineNumber());
    }
}
